package io.github.zatter.qiniucorejava.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.zatter.qiniucorejava.utils.model.TextApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

@Slf4j
public class VoiceToTextService {

    // 七牛云语音转文字接口配置
    private static final String API_KEY = "sk-610453bad9743dfb294ae3234ada68874c4c1640e6c4cd716dfac043a774eb21"; // 替换为你的API密钥
    private static final String ASR_API_URL = "https://openai.qiniu.com/v1/voice/asr";
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public VoiceToTextService() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();

        // 配置超时时间（语音转文字需要较长处理时间）
        ((org.springframework.http.client.SimpleClientHttpRequestFactory) restTemplate.getRequestFactory())
                .setConnectTimeout(Duration.ofSeconds(30));
        ((org.springframework.http.client.SimpleClientHttpRequestFactory) restTemplate.getRequestFactory())
                .setReadTimeout(Duration.ofSeconds(120));
    }

    /**
     * 调用七牛云语音转文字接口（通过音频URL）
     * @param audioUrl 音频文件的URL地址（如http://idh.qnaigc.com/voicetest.mp3）
     * @return 识别后的文本结果
     */
    public String convertVoiceToTextByUrl(String audioUrl) {
        try {
            // 1. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + API_KEY);
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 2. 构建请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", "asr"); // 固定模型值

            // 构建audio对象
            ObjectNode audioNode = objectMapper.createObjectNode();
            audioNode.put("format", "asr"); // 固定格式值
            audioNode.put("url", audioUrl); // 音频URL
            requestBody.set("audio", audioNode);

            // 3. 发送POST请求
            HttpEntity<String> request = new HttpEntity<>(
                    objectMapper.writeValueAsString(requestBody),
                    headers
            );
            log.info("调用七牛云语音转文字接口，音频URL：{}", audioUrl);

            ResponseEntity<String> response = restTemplate.postForEntity(
                    ASR_API_URL,
                    request,
                    String.class
            );

            // 4. 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                log.info("语音转文字接口返回结构体："+response.getBody());
                TextApiResponse textApiResponse = JSON.parseObject(response.getBody(), TextApiResponse.class);
                log.info("语音转文字返回的结果："+textApiResponse.getData().getResult().getText());
                return textApiResponse.getData().getResult().getText();
            } else {
                return "错误：接口返回状态码 " + response.getStatusCode() + "，响应内容：" + response.getBody();
            }

        } catch (Exception e) {
            log.error("语音转文字失败", e);
            return "处理错误：" + e.getMessage();
        }
    }

    /**
     * 调用七牛云语音转文字接口（通过Base64编码的音频数据）
     * @param base64Audio Base64编码的音频数据
     * @param format 音频格式（如mp3、wav等）
     * @return 识别后的文本结果
     */
    public String convertVoiceToTextByBase64(String base64Audio, String format) {
        try {
            // 1. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + API_KEY);
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 2. 构建请求体（使用base64数据）
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", "asr");

            ObjectNode audioNode = objectMapper.createObjectNode();
            audioNode.put("format", format); // 音频格式（如mp3、wav）
            audioNode.put("data", base64Audio); // Base64编码的音频数据
            requestBody.set("audio", audioNode);

            // 3. 发送POST请求
            HttpEntity<String> request = new HttpEntity<>(
                    objectMapper.writeValueAsString(requestBody),
                    headers
            );
            log.info("调用七牛云语音转文字接口，音频格式：{}", format);

            ResponseEntity<String> response = restTemplate.postForEntity(
                    ASR_API_URL,
                    request,
                    String.class
            );

            // 4. 处理响应（同URL方式）
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                log.info("语音转文字接口返回：{}", response.getBody());
                JsonNode jsonNode = objectMapper.readTree(response.getBody());
                String result = jsonNode.path("result").asText();

                if (result != null && !result.isEmpty()) {
                    return result;
                } else {
                    return "错误：未从响应中提取到识别结果";
                }
            } else {
                return "错误：接口返回状态码 " + response.getStatusCode() + "，响应内容：" + response.getBody();
            }

        } catch (Exception e) {
            log.error("语音转文字失败", e);
            return "处理错误：" + e.getMessage();
        }
    }
}
